﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;

namespace WCS.Application.Helper;

public class MyJsonHelper
{

    public static DataTable ToDataTable(IEnumerable<dynamic> val)
    {
        return JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(val));
    }
    public static DataTable ToDataTable(string val)
    {
        return JsonConvert.DeserializeObject<DataTable>(val);
    }
    public static JObject ToJObject(string val)
    {
        if (string.IsNullOrEmpty(val))
        {
            return new JObject();
        }
        var reader = new JsonTextReader(new StringReader(val));
        reader.FloatParseHandling = FloatParseHandling.Decimal;

        return JObject.Load(reader);
    }

    /// <summary>
    /// JObject转换Key值
    /// </summary>
    /// <param name="inputObject">输入的JSON对象</param>
    /// <param name="propertyPairs">旧key与新key对应关系</param>
    /// <returns>转换后的JObject</returns>
    public static JObject JObjectKeyConvert(JObject inputObject, Dictionary<string, string> propertyPairs)
    {
        var jObjectResult = new JObject();

        try
        {
            if (null != inputObject && 0 < inputObject.Count && null != propertyPairs && 0 < propertyPairs.Count)
            {
                var lstKey = propertyPairs.Keys.ToList();
                var lstObjectKey = inputObject.Properties().ToList();
                for (int i = 0; i < lstObjectKey.Count(); i++)
                {
                    var p = lstObjectKey[i];

                    //老的key
                    var sOldKey = lstKey.FirstOrDefault(k => 0 == string.Compare(p.Name, (k.IndexOf(",") != -1 ? k.Split(',')[0] : k), StringComparison.OrdinalIgnoreCase));
                    //新的key
                    string sNewKey = (!string.IsNullOrEmpty(sOldKey)) ? propertyPairs[sOldKey] : p.Name;

                    if (!propertyPairs.Values.Contains(sNewKey))
                    {
                        continue;
                    }

                    //当前循环的属性值
                    var singleValue = inputObject[p.Name];
                    jObjectResult.Add(sNewKey, singleValue);
                }
            }
        }
        catch (Exception ex)
        {
            //logger.Error("异常类型: \t" + ex.GetType());
            //logger.Error("异常描述：\t" + ex.Message);
            //logger.Error("异常方法：\t" + ex.TargetSite);
            //logger.Error("异常堆栈：\t" + ex.StackTrace);
            jObjectResult = null;
        }
        return jObjectResult;
    }

    public static Dictionary<string, object> DictionaryKeyConvert(JObject inputObject, Dictionary<string, string> propertyPairs)
    {
        var jObjectResult = new Dictionary<string, object>();

        try
        {
            if (null != inputObject && 0 < inputObject.Count && null != propertyPairs && 0 < propertyPairs.Count)
            {
                var lstKey = propertyPairs.Keys.ToList();
                var lstObjectKey = inputObject.Properties().ToList();
                for (int i = 0; i < lstObjectKey.Count(); i++)
                {
                    var p = lstObjectKey[i];

                    //老的key
                    var sOldKey = lstKey.FirstOrDefault(k => 0 == string.Compare(p.Name, (k.IndexOf(",") != -1 ? k.Split(',')[0] : k), StringComparison.OrdinalIgnoreCase));
                    //新的key
                    string sNewKey = (!string.IsNullOrEmpty(sOldKey)) ? propertyPairs[sOldKey] : p.Name;

                    if (!propertyPairs.Values.Contains(sNewKey))
                    {
                        continue;
                    }

                    //当前循环的属性值
                    var singleValue = inputObject[p.Name];
                    jObjectResult.Add(sNewKey, singleValue);
                }
            }
        }
        catch (Exception ex)
        {
            jObjectResult = null;
        }
        return jObjectResult;
    }
}
